/**
 * Created by Dalyn on 2017/2/28.
 * 采购-已签订单
 */
import React from "react";
import { hashHistory } from 'react-router';
import Relay from "react-relay";
import ListOrderMutation from "../mutation/ListOrderMutation";
import Check from '../Check';
import Order_Item from './Order_Item';
import Util from "../../../util/Util"
import Pagination from "../Pagination";
import Reactkey from "../../../util/ReactKey";
import OrderPurch_Item from "./OrderPurch_Item";
import "./css/Order_OrderPurch_item.css";
import Modal_PayFor from "./Modal_PayFor";
import { Table,message,Menu, Dropdown, Icon,Tooltip } from 'antd';
import InputBox from "../../../common/InputBox";
import {Button} from 'fly';
import Modal_Supplement  from "./Modal_Supplement"
import BatchHint  from "./BatchHint";
import Finished  from "./Finished"

import FinishOrderMutation from "../mutation/FinishOrderMutation"
import OrderDetailSupplement from '../order_detail/OrderDetailSupplement'
/*信息列表*/
export default class ListOrder extends React.Component{
    constructor(props){
        super(props);
        this.state={
            orders:[],
            totalresult:0,
            placeholder:'请输入企业名称进行搜索',
            loading:true,
        };
        this.enterpriseId = sessionStorage.getItem('enterpriseId');
        this.permissionId = sessionStorage.getItem('permissionId');
        this.uid = sessionStorage.getItem('uid');
        this.serviceType = sessionStorage.getItem('serviceType');
        this.odtail='1';
        this.ods='3,4';
        this.goodtypeobj={'1':'成衣','2':'辅料','3':'面料','4':'印染','5':'纱线'}
        this.odsobj={'-1':'待创建',0:'待发布',1:'待接单',2:'待签订',3:'已签订',4:'交易完成'};
        this.oddstatus=["全部:1,2,3,4","已发布:1,2","已签订:3","已完成:4"];
        this.enid = sessionStorage.getItem('enterpriseId');

        this.order_purch_oid = '';
        this.order_purch_account = '';
        this.order_purch_status = '';
        this.order_purch_type = '';

    }
    componentWillMount(){
        this.queryorderlist(10,1);
    }
    componentDidMount(){
        // this.refs['df'+0].chose();
    }

    queryorderlist(pageSize,pageNum){
        let enName = this.refs.enName ? this.refs.enName.state.text : '';
        let styleNo = this.refs.styleNo ? this.refs.styleNo.state.text : '';

        let orderType = '';
        if(this.serviceType ==1){
            orderType = '1,2,3'
        }else if(this.serviceType ==2){
            orderType = '2'
        }else if(this.serviceType ==3){
            orderType = '4,5'
        }else if(this.serviceType ==4){
            orderType = '4'
        }else if(this.serviceType ==5){
            orderType = '5'
        }else if(this.serviceType ==6){
            orderType = '1,2,3'
        }
        this.order_purch_oid = '';
        Relay.Store.commitUpdate(
            new ListOrderMutation({
                pageSize: pageSize,
                pageNum: pageNum,
                status:this.ods,
                type:'2',
                enId:this.enid,
                enName:enName||'',
                styleNo:styleNo || '',
                searchType:2,
                orderType:orderType
            }),
            {
                onFailure: () => {
                    message.info('请求失败');
                    this.setState({
                        loading:false,
                    });
                },
                onSuccess: (response) => {
                    let errorCode = response.listOrder.listOrder.errorCode;
                    if(errorCode=='0'){
                        let orders = response.listOrder.listOrder.orders
                        let totalResult = response.listOrder.listOrder.totalResult
                        this.setState({
                            orders:orders,
                            totalresult:totalResult,
                            loading:false,
                        });
                    }else {
                        this.setState({
                            loading:false,
                        });
                        if (errorCode == 500){
                            message.error('服务器错误,请联系系统管理员');
                        }
                    }
                }
            }
        )
    }

    handleclick(){

    }

    choseoddetail(indexd,value){
        this.odtail = value
        this.oddetail.map((context,index)=>{
            if(indexd!=index){
                this.refs['de'+index].unchose();
            }
        });
        this.queryorderlist(10,1);
        this.refs.pagination.setState({
            text:1
        });
    }

    choseodorderstatus(indexd,value){
        this.ods = value;
        this.oddstatus.map((context,index)=>{
            if(indexd!=index){
                this.refs['df'+index].unchose();
            }
        });
        this.queryorderlist(10,1);
        this.refs.pagination.setState({
            text:1
        });
    }

    addorderstatus(){
        return this.oddstatus.map((con,index)=>{
            return(
                <Order_Item choseodstate={this.choseodorderstatus.bind(this)} key={index+'_'} ref={'df'+index} index={index} con={con}/>
            )

        })
    }

    check(){
        this.refs.check.setState({
            visible : true
        })
    }

    reloadList(){
        this.queryorderlist(10,1);
    }

    addDepartmenlist(){
        return this.state.orders.map((context,index)=>{
            let date = Util.dateFormat(context.createDate);
            let ods=this.odsobj[context.status];
            return (
                <OrderPurch_Item context={context} key = {Reactkey.key} index={index} _onChangeBoxCallBack = {this._onChangeBoxCallBack.bind(this)}
                                 ref={'order_item'+index} reloadList={this.reloadList.bind(this)}/>
            );
        });
    }

    _onChangeBoxCallBack(chooseindex,oid,account,check,status,type){
        if(check){
            this.order_purch_oid = oid;
            this.order_purch_account = account;
            this.order_purch_status = status;
            this.order_purch_type = type
        }else{
            this.order_purch_oid = '';
            this.order_purch_account = '';
            this.order_purch_status = '';
            this.order_purch_type = '';
        }
        this.state.orders.map((context,index)=>{
            if(chooseindex != index){
                this.refs['order_item'+index]._onChangeBoxFalse();
            }
        });
    }

    stroke(){

    }

    status(){
        return this.oArr.map((item,index)=>{
            return (
                <span style={{width:80,height:27,borderRadius:"8px",background:"#ccc",display:"block"}} onClick={this.stroke.bind(this)}>{item}</span>
            )
        })
    }

    createorder(){
        hashHistory.push('/createorder')
    }

    onSure(size,num){
        this.setState({
            loading:true,
        },this.queryorderlist(size,num))
    }

    onfocusInput(){
        this.setState({
            placeholder:''
        })
    }

    bluronInput(){
        this.setState({
            placeholder:'请输入企业名称进行搜索'
        })
    }
    /*申请付款*/
    _PayFor(){
        message.config({
            top: 70,
            duration: 1.5,
        });
        if(this.order_purch_oid == ''){
            message.info('请选择订单');
            return;
        }
        if(this.order_purch_status == 4){
            message.info('交易已完成');
            return;
        }
        if(this.order_purch_status == 0){
            message.info('订单还未发布');
            return;
        }

        if(this.order_purch_status == 1){
            message.info('订单还未接收');
            return;
        }

        this.refs.modal_payfor.setState({
            visible:true,
            oid:this.order_purch_oid,
            account:this.order_purch_account
        });
    }
    /*补充合同*/
    _Supplement(account){
        // message.config({
        //     top: 70,
        //     duration: 1.5,
        // });
        //
        // if(this.order_purch_oid == ''){
        //     message.info('请选择订单');
        //     return;
        // }
        // if(this.order_purch_status == 4){
        //     message.info('交易已完成');
        //     return;
        // }
        // if(this.order_purch_status == 0){
        //     message.info('订单还未发布');
        //     return;
        // }
        // if(this.order_purch_status == 1){
        //     message.info('订单还未接收');
        //     return;
        // }
        // if(this.order_purch_status == 2){
        //     message.info('订单还未签订');
        //     return;
        // }
        let oid = this.order_purch_oid;
        this.refs.ordersupp.setState({
            visible: true,
            oid: oid,
            account: account,
        });
        // hashHistory.push({pathname:'/OrderIndex/',state:{
        //     'oid':oid,
        //     "defaultActiveKey":1,
        // }});
    }
    /*完成交易*/
    _DealFinished(){
        message.config({
            top: 70,
            duration: 1.5,
        });
        if(this.order_purch_oid == ''){
            message.info('请选择订单');
            return;
        }
        if(this.order_purch_status == 4){
            message.info('交易已完成');
            return;
        }
        if(this.order_purch_status == 0){
            message.info('订单还未发布');
            return;
        }

        if(this.order_purch_status == 1){
            message.info('订单还未接收');
            return;
        }

        Relay.Store.commitUpdate(
            new FinishOrderMutation({
                orderId:this.order_purch_oid,
            }),
            {
                onFailure: () => {
                    message.info('请求失败');
                },
                onSuccess: (response) => {
                    let errorCode = response.finishOrder.finishOrder.errorCode;
                    let value  = response.finishOrder.finishOrder.value;
                    if(errorCode==0){
                        message.success('交易成功');
                        let _pageNum = this.refs.pagination.state.text
                        this.queryorderlist(10, _pageNum);
                        this.setState({
                            visible:false
                        });
                    }else{
                        message.info('交易金额不符，请填写合同补充');
                    }
                }
            }
        )

    }

    _SearchByEn(){
        this.queryorderlist(10,1);
        /*点击搜索，页码为1*/
        this.refs.pagination.setState({
            text:1
        })
    }
    /*修改-0602*/
    jumpTree(oid){
        hashHistory.push({pathname:'/ordertree/',state:{'oid':oid}})
    }
    dosomebystatus(status,oid,oty){
        switch (status){
            case 0:
                Relay.Store.commitUpdate(
                    new DelOrderMutation({
                        orderId : oid
                    }),
                    {
                        onFailure: () => {

                        },
                        onSuccess: (response) => {
                            this.props.reloadList();
                        }
                    }
                )

                return;
            case 1:
                return;
            case 2:
                this.jumpDetil(oty,oid)
                return;
            case 3:
                // hashHistory.push({pathname:'/receiveGoods/',state:{'oid':oid}})
                hashHistory.push({pathname:'/receiveGoodsItem/',state:{'oid':oid}})
                return;
            case 4:
                return;

        }

    }
    /*跳转上下游关系*/
    jumpstreamshow(oid){
        hashHistory.push({pathname:'/orderstreamshow/',state:{'oid':oid}})
    }
    /*确认框-点击确定*/
    BatchHintOk(type,value){
        switch (type){
            case "complete":
                Relay.Store.commitUpdate(
                    new FinishOrderMutation({
                        orderId:value,
                    }),
                    {
                        onFailure: () => {
                            message.info('请求失败');
                        },
                        onSuccess: (response) => {
                            let errorCode = response.finishOrder.finishOrder.errorCode;
                            let value  = response.finishOrder.finishOrder.value;
                            if(errorCode==0){
                                message.success('交易成功');
                                let _pageNum = this.refs.pagination.state.text
                                this.queryorderlist(10, _pageNum);
                                this.setState({
                                    visible:false
                                });
                            }else{
                                message.info('交易金额不符，请填写合同补充');
                            }
                        }
                    }
                )
                break;
        }
    }
    render(){
        let { orders } = this.state;
        const columns = [
            {
                title: '订单编号',
                dataIndex: 'oid',
                key: 'oid',
                width: 200,
                render: (text, record, index) => {
                    if(record.status >= 3 && (this.serviceType==1||this.serviceType==3) && record.orderType != '1'){
                        return  (
                            <span title={record.oid} className="order_orderpurch_item_from_td_oid_otyp1" onClick={this.jumpstreamshow.bind(this,record.oid)}>{record.oid}</span>
                        )
                    }else {
                        return(
                            <span title={record.oid} className="order_orderpurch_item_from_td_oid">{record.oid}</span>
                        )
                    }
                    /*return  record.orderType ==1?
                     <span title={record.oid} className="order_orderpurch_item_from_td_oid_otyp1" onClick={this.jumpTree.bind(this,record.oid)}>{record.oid}</span>
                     :
                     <span title={record.oid} className="order_orderpurch_item_from_td_oid">{record.oid}</span>*/
                },
            },
            {
                title: '款号',
                dataIndex: 'orderGoodsStyleNos',
                key: 'orderGoodsStyleNos',
                render:(text, record, index) =>{
                    return text && text.length > 8 ? (
                        <Tooltip
                            placement="top"
                            title={text}
                            // getPopupContainer={() => document.getElementsByClassName("order_inoutDetailModal")[0]}
                        >
                            <span className='order_detail_remark'>{text}</span>
                        </Tooltip>
                    ) : <span>{text}</span>
                }
            },
            {
                title: '供应方',
                dataIndex: 'partBName',
                key: 'partBName',
                width: 260,
                render:(text, record, index) =>{
                    return <span title={record.partBName} className="">{record.partBName}</span>
                }
            },
            {
                title: '商品类型',
                dataIndex: 'orderType',
                key: 'orderType',
                render:(text, record, index) =>{
                    return <span className="">{this.goodtypeobj[record.orderType]}</span>
                }
            },
            {
                title: '数量',
                dataIndex: 'orderGoodsNum',
                key: 'orderGoodsNum',
                render:(text, record, index) =>{
                    return <span className="">{Number(record.orderGoodsNum).toFixed(3)}</span>
                }
            },
            {
                title: '剩余数量',
                dataIndex: 'remainOrderGoodsNum',
                key: 'remainOrderGoodsNum',
                render:(text, record, index) =>{
                    return <span className="">{Number(record.orderGoodsNum-record.remainOrderGoodsNum).toFixed(3)}</span>
                }
            },
            {
                title: '订单金额（元）',
                dataIndex: 'account',
                key: 'account',
                render:(text, record, index) =>{
                    return <span className="">{record.account/100}</span>
                }
            },
            {
                title: '付款金额（元）',
                dataIndex: 'payAccount',
                key: 'payAccount',
                render:(text, record, index) =>{
                    return <span className="">{record.payAccount/100}</span>
                }
            },
            {
                title: '订单状态',
                dataIndex: 'status',
                key: 'status',
                render:(text, record, index) =>{
                    return <span className="">{this.odsobj[record.status]}</span>
                }
            },
            {
                title: '操作',
                dataIndex: 'operate',
                key: 'operate',
                width: 100,
                render:(text, record, index) =>{
                    let _this = this;
                    const fun = {
                        jumpDetail:()=>{
                            hashHistory.push({pathname:'/OrderIndex/',state:{
                                'record':record,
                                "defaultActiveKey":1,
                            }})
                        },
                        jumpReject:()=>{
                            hashHistory.push({pathname:'/OrderIndex/',state:{
                                'record':record,
                                "defaultActiveKey":5,
                            }})
                        },
                        jumpApplyPay:()=>{
                            _this.order_purch_oid = record.oid;
                            _this.order_purch_status = record.status;
                            _this.order_purch_account = record.account;
                            _this._PayFor();
                        },
                        jumpSupplement:()=>{
                            _this.order_purch_oid = record.oid;
                            _this.order_purch_status = record.status;
                            _this.order_purch_type = record.orderType;
                            _this._Supplement(record.account);
                        },
                        jumpComplete:()=>{
                            /*{
                             record.isOnlineBalance == 1 ? (
                             Modal.confirm({
                             title: '该订单需要通过平台进行结算，确认交易完成后，会自动生成代付款协议，需甲乙双方同平台三方进行签订，代付款协议可在合同管理中进行下载',
                             content: '',
                             width: 600,
                             onOk() {
                             _this.order_purch_oid = record.oid;
                             _this.order_purch_status = record.status;
                             _this._DealFinished();
                             },
                             onCancel() {
                             // console.log('Cancel');
                             },
                             })
                             ) : (
                             Modal.confirm({
                             title: '确定完成本次交易吗?',
                             content: '',
                             onOk() {
                             _this.order_purch_oid = record.oid;
                             _this.order_purch_status = record.status;
                             _this._DealFinished();
                             },
                             onCancel() {
                             // console.log('Cancel');
                             },
                             })
                             )
                             }*/
                            if(record.isOnlineBalance == 1){
                                let  message = "确定完成本次交易吗?";
                                this.refs.finished.showWindow(true,message,"warning","complete",record.oid);
                            }else {
                                let  message = "确定完成本次交易吗?";
                                this.refs.batchHint.showWindow(true,message,"warning","complete",record.oid);
                            }
                        },
                        jumpChain:()=>{
                            hashHistory.push({pathname:'/ordertree/',state:{
                                'oid':record.oid,
                            }})
                        },
                        jumpProcess:()=>{
                            hashHistory.push({pathname:'/OrderIndex',state:{
                                record:record,
                                defaultActiveKey:10,
                                showProofing:1
                            }})
                        },
                    };
                    const menuItem = [
                        {key:"detail",iconType:"file-text",text:"查看详情",onClick:()=>{fun.jumpDetail();}},
                        {key:"dayang",iconType:"bars",text:"打样管理",onClick:()=>{fun.jumpProcess();}},
                        {key:"reject",iconType:"export",text:"收货",onClick:()=>{fun.jumpReject();}},
                        {key:"applyPay",iconType:"red-envelope",text:"申请付款",onClick:()=>{fun.jumpApplyPay();}},
                        {key:"supplement",iconType:"file-add",text:"补充合同",onClick:()=>{fun.jumpSupplement();}},
                        {key:"complete",iconType:"check-circle-o",text:"完成交易",onClick:()=>{fun.jumpComplete();}},
                        {key:"chain",iconType:"share-alt",text:"查看供应链",onClick:()=>{fun.jumpChain();}},
                    ];
                    const menu = (
                        <Menu
                            className="listOrder_purchase_dropDown_menu"
                        >
                            {
                                menuItem.map((v,i)=>{
                                    if(record.status == 3 ){
                                        {/*已签订*/}
                                        if(v.key == "chain"){
                                            {/*查看供应链*/}
                                            if(this.serviceType == 6 ||this.serviceType == 1){
                                                return (
                                                    <Menu.Item key={v.key}>
                                                        <span className="listOrder_purchase_dropDown_menuItem" onClick={v.onClick}><Icon type={v.iconType} className="listOrder_purchase_dropDown_menuItem_icon"/>{v.text}</span>
                                                    </Menu.Item>
                                                )
                                            }
                                        } else if (v.key == 'applyPay') {
                                            if (record.isOnlineBalance == 1) {
                                                return (
                                                    <Menu.Item key={v.key}>
                                                        <span className="listOrder_purchase_dropDown_menuItem" onClick={v.onClick}><Icon type={v.iconType} className="listOrder_purchase_dropDown_menuItem_icon"/>{v.text}</span>
                                                    </Menu.Item>
                                                )
                                            }
                                        }else if(v.key == "dayang"){//只有成衣订单可见-已签订
                                            if(record.orderType == 1){
                                                return (
                                                    <Menu.Item key={v.key}>
                                                        <span className="listOrder_purchase_dropDown_menuItem" onClick={v.onClick}
                                                        ><Icon type={v.iconType} className="listOrder_purchase_dropDown_menuItem_icon"/>{v.text}</span>
                                                    </Menu.Item>
                                                )
                                            }
                                        } else {
                                            {/*其他四个全有*/}
                                            return (
                                                <Menu.Item key={v.key}>
                                                    <span className="listOrder_purchase_dropDown_menuItem" onClick={v.onClick}><Icon type={v.iconType} className="listOrder_purchase_dropDown_menuItem_icon"/>{v.text}</span>
                                                </Menu.Item>
                                            )
                                        }
                                    }else if(record.status == 4 ){
                                        {/*交易完成*/}
                                        if(v.key == "chain"){
                                            {/*查看供应链*/}
                                            if(this.serviceType == 6 ||this.serviceType == 1){
                                                return (
                                                    <Menu.Item key={v.key}>
                                                        <span className="listOrder_purchase_dropDown_menuItem" onClick={v.onClick}><Icon type={v.iconType} className="listOrder_purchase_dropDown_menuItem_icon"/>{v.text}</span>
                                                    </Menu.Item>
                                                )
                                            }
                                        }else if(v.key == "detail"){
                                            {/*详情*/}
                                            return (
                                                <Menu.Item key={v.key}>
                                                    <span className="listOrder_purchase_dropDown_menuItem" onClick={v.onClick}><Icon type={v.iconType} className="listOrder_purchase_dropDown_menuItem_icon"/>{v.text}</span>
                                                </Menu.Item>
                                            )
                                        }
                                    }
                                })
                            }
                        </Menu>
                    );
                    return (
                        <Dropdown overlay={menu} placement="bottomLeft">
                            <Icon type="ellipsis" className="listOrder_purchase_dropDown_icon"/>
                        </Dropdown>
                    )
                }
            },
        ];
        return (
            <div className="order_box">
                {/*<p style={{height:28,marginTop:"20px",}} >
                 <span style={{display:"block",float:"left",marginLeft:"20px",paddingRight:"15px",eight:28,lineHeight:"28px",fontSize:"14px",fontFamily:"Microsoft Yahei"}}>订单状态：</span>
                 {
                 this.addorderstatus()
                 }
                 </p>*/}
                <div className="order_saleandre_frome_search_box">
                    {/*<input className=" pro_overflow_inputSty" defaultvalute="请输入订单号"*/}
                    {/*onFocus={this.onfocusInput.bind(this)}*/}
                    {/*onBlur={this.bluronInput.bind(this)} ref={'enName'}/>*/}
                    <div style={{display:"flex",alignItems: 'center',marginLeft:'20px',marginRight: '-3px'}}>
                        款号：
                        <InputBox className="order_saleandre_frome_search_input pro_overflow_inputSty "
                                  space={20}
                                  ref={"styleNo"}
                                  defaultvalute="请输入款号"
                                  changeon={this.bluronInput.bind(this,"styleNo")}
                        />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
                        供应方：
                        <InputBox className="order_saleandre_frome_search_input pro_overflow_inputSty "
                                  space={20}
                                  ref={"enName"}
                                  defaultvalute="请输入企业名称"
                                  changeon={this.bluronInput.bind(this,"enName")}
                        />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
                        <Button onClick={this._SearchByEn.bind(this)}>搜索</Button>
                    </div>

                    {/*<span className="order_saleandre_frome_search_div" onClick={this._SearchByEn.bind(this)}>搜索</span>*/}
                </div>
                <div style={{background:"#fff",margin:'20px',position:"relative"}}>
                    {/*修改-0602*/}
                    <Table
                        columns={columns}
                        dataSource={orders}
                        className="order_table listOrder_purchase_table"
                        pagination={false}
                        rowKey={record => record.oid}
                        loading={this.state.loading}
                    />
                    <Check ref={"check"}/>
                    <Pagination eachSize={10} dataSize={this.state.totalresult} onSure={this.onSure.bind(this)} ref={'pagination'}/>
                </div>
                <BatchHint ref={"batchHint"} _handleOk={this.BatchHintOk.bind(this)} />
                <Finished ref={"finished"} _handleOk={this.BatchHintOk.bind(this)} />
                <Modal_PayFor ref={'modal_payfor'} uid={this.uid}/>
                <Modal_Supplement ref={'modal_supplement'} uid={this.uid}/>
                <OrderDetailSupplement visible={this.state.visible} ref={'ordersupp'}/>
            </div>

        )
    }
}
